package core

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"muziai-server/global"
	"time"
)

var errCount = 0

func InitGorm() *gorm.DB {

	//连接MYSQL, 获得DB类型实例，用于后面的数据库读写操作。
	db, err := gorm.Open(mysql.Open(global.Config.Mysql.Dsn()), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		errCount++
		if errCount > global.Config.Mysql.ReconnectionTimes {
			panic("连接数据库失败，" + err.Error())
		}
		logrus.Warn(err.Error())
		time.Sleep(time.Duration(global.Config.Mysql.ReconnectTime) * time.Second)
		logrus.Warnf("第%d次重连", errCount)
		return InitGorm()
	}
	logrus.Infof("连接成功")
	// 连接成功
	fmt.Println(db)

	return db

}
